package com.channel.temperature.collect.app.bleupdate;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.inuker.bluetooth.library.BluetoothClient;
import com.inuker.bluetooth.library.beacon.Beacon;
import com.inuker.bluetooth.library.beacon.BeaconItem;
import com.inuker.bluetooth.library.beacon.BeaconParser;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.channel.temperature.collect.R;
import com.channel.temperature.collect.app.util.ClientManager;
import com.channel.temperature.collect.app.util.MyUtil;

import java.util.ArrayList;
import java.util.List;

public class ScanBLEActivity extends Activity {

    // 控件声明
    ListView blelistView = null;

    RadioGroup mRadioGroup;
    RadioButton rbt1;
    RadioButton rbt2;
    int firmWareZipType = 1;//1:ble_service 2：ble_service_ota

    private DeviceListAdapter1 mAdapter;
    private List<SearchResult> mDevices;
    private BluetoothClient mClient;
    private Button scanButton;
    private boolean isScaning = false; //扫描状态标志位

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_ble);
        mRadioGroup = findViewById(R.id.radio_group);
        rbt1 = findViewById(R.id.rbt1);
        rbt2 = findViewById(R.id.rbt2);
        //单例模式创建client对象
        mClient = ClientManager.getClient();
        blelistView = findViewById(R.id.device_list);
        scanButton = findViewById(R.id.scan_btn);
        mDevices = new ArrayList<SearchResult>();
        mAdapter = new DeviceListAdapter1(this);
        blelistView.setAdapter(mAdapter);

        initRadioButtonLayout();
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rbt1:
                        rbt1.setChecked(true);
                        rbt2.setChecked(false);
                        firmWareZipType = 1;
                        break;
                    case R.id.rbt2:
                        firmWareZipType = 2;
                        rbt1.setChecked(false);
                        rbt2.setChecked(true);
                        break;
                }
            }
        });
        // 请求打开蓝牙
        blelistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final SearchResult result = (SearchResult) parent.getAdapter().getItem(position);
                Beacon beacon = new Beacon(result.scanRecord);
                BeaconItem extra = null;
                for (BeaconItem item : beacon.mItems) {
                    if (item.type == 0XFF) {
                        extra = item;
                    }
                }

                if (extra != null) {
                    BeaconParser beaconParser = new BeaconParser(extra);
                    int firstByte = beaconParser.readByte(); // 读取第1个字节
                    int secondByte = beaconParser.readByte(); // 读取第2个字节
                    int lockstatus = beaconParser.readByte(); //读取第3个字节 锁状态指示

                    boolean isDoorOpen = beaconParser.getBit(lockstatus, 4);  //获取第3字节的第4bit 门锁状态
                    beaconParser.readShort();                     //电池信息  4,5
                    beaconParser.readByte(); //按钮按下计时器   6    新东的是4
                    int mode = ((beaconParser.readByte() >> 4) & 0xff);
                    byte versionName = (byte) beaconParser.readByte();   //  锁类型  高4bit:当前程序模式    低4bit:锁类型 (3：蓝牙挂锁  )
//                        Log.e("测试", "测试 " + versionName + " " + String.format("V%2x", versionName));

                    String dataString = MyUtil.bytesToHexString(extra.bytes);
                    Log.e("dataString", "dataString : " + dataString);
                    String versionCode = dataString.substring(14, 16);
                    int versionCodeResult = 0;
                    try {
                        versionCodeResult = Integer.parseInt(versionCode);
                    } catch (NumberFormatException e) {

                    }

                    Intent intent = new Intent(getApplicationContext(), OTA_Uart_Active.class);
                    intent.putExtra("DEVICE_NAME", result.getName());
                    intent.putExtra("DEVICE_MAC", result.getAddress());
                    intent.putExtra("isDoorOpenTR", isDoorOpen);
                    intent.putExtra("version", versionCodeResult);
                    intent.putExtra("binType", firmWareZipType);
                    startActivity(intent);
                }


//                finishActivity(1);
            }
        });
        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isScaning) {
                    stopScan(mClient);
                } else if (!isScaning) {
                    mDevices.clear();
                    mAdapter.setDataList(mDevices);
                    startScan(mClient);
                }
            }
        });
        startScan(mClient);
    }

    public void initRadioButtonLayout() {
        if (firmWareZipType == 1) {
            rbt1.setChecked(true);
            rbt2.setChecked(false);
        } else if (firmWareZipType == 2) {
            rbt1.setChecked(false);
            rbt2.setChecked(true);
        } else {
            rbt1.setChecked(false);
            rbt2.setChecked(true);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        stopScan(mClient);
    }

    /**
     * 手动停止扫描设备
     *
     * @param mClient
     */
    private void stopScan(BluetoothClient mClient) {
        mClient.stopSearch();
    }

    /**
     * 开始扫描设备
     *
     * @param mClient
     */
    private void startScan(BluetoothClient mClient) {

        //扫描设备5秒
        SearchRequest request = new SearchRequest.Builder().searchBluetoothLeDevice(30000).build();

        mClient.search(request, new SearchResponse() {
            @Override
            public void onSearchStarted() {
                isScaning = true;
                scanButton.setText("取消扫描");
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                Log.e("onDeviceFounded", "onDeviceFounded : " + device.getName());
                if (device.getName() == null || device.getName().equals("NULL")) {

                } else {
                    if (device.getName().contains("TZWM23A")) {
                        if (!mDevices.contains(device)) {
                            mDevices.add(device);
                            mAdapter.setDataList(mDevices);
                        }
                    }
                }


                if (mDevices.size() > 0) {

                }
            }

            @Override
            public void onSearchStopped() {
                isScaning = false;
                scanButton.setText(getResources().getString(R.string.start_scan));
            }

            @Override
            public void onSearchCanceled() {
                isScaning = false;
                scanButton.setText(getResources().getString(R.string.start_scan));
            }
        });
    }

}
